import cp from "child_process";
import path from "path";
import fs from "fs";
import { app, ipcMain } from "electron";
import type { BrowserWindow } from "electron";
import log from "electron-log";
export default (win: BrowserWindow) => {
  const pdfDir = path.join(app.getPath("userData"), `./print-temp`);
  log.info("pdf-dir", pdfDir);
  ipcMain.on("printPDF", (e, arg) => {
    const writeFile = () => {
      const fileName = Date.now();
      const pdfPath = path.join(pdfDir + `/${fileName}.pdf`);
      log.info("pdf-path", pdfPath);
      fs.writeFile(pdfPath, arg.baseCode, { encoding: "utf8" }, (err) => {
        const printExePath = process.env.VITE_DEV_SERVER_URL
          ? app.getAppPath()
          : path.dirname(app.getPath("exe"));
        log.info("printExePath", printExePath);
        // 失败
        if (err) {
          // 向渲染进程发送消息通知失败
          e.reply("defeatedDialog", err);
        } else {
          switch (process.platform) {
            case "win32":
              const commend =arg.type==="print"? `SumatraPDF-3.4.6-64.exe -print-dialog ${pdfPath}`:`SumatraPDF-3.4.6-64.exe ${pdfPath}`
              cp.exec(
                commend,
                {
                  windowsHide: true,
                  cwd: printExePath,
                },
                (e) => {
                  fs.unlink(pdfPath, (e) => {
                    log.info("print-pdf-err", e);
                  });
                  console.log("print-pdf-file-err", e);
                  if (e) {
                    throw e;
                  }
                }
              );
              break;
            default:
              throw new Error("Platform not supported.");
          }
        }
      });
    };
    if (fs.existsSync(pdfDir)) {
      writeFile();
    } else {
      fs.mkdir(pdfDir, { recursive: true }, (err) => {
        if (err) {
          throw err;
        } else {
          writeFile();
        }
      });
    }
  });
};
